<template>
  <div class="app-container">
    <!-- 移除独立的 el-loading 组件 -->
    <!-- 直接在容器上使用 v-loading 指令 -->
    <div v-loading="loading"
         :element-loading-text="loadingText"
         element-loading-background="rgba(0, 0, 0, 0.7)">

      <el-card class="box-card" v-loading="cardLoading">
        <div slot="header" class="clearfix">
          <span>预约信息</span>
        </div>

        <!-- 日期选择器 -->
        <div class="date-picker">
          <div class="date-picker-wrapper">
            <!-- 左箭头 -->
            <div class="arrow-button left"
                 :class="{ disabled: !canScrollLeft }"
                 @click="canScrollLeft && scrollDates('left')">
              <i class="el-icon-arrow-left"></i>
            </div>

            <!-- 日期滚动区域 -->
            <div class="date-scroll" ref="dateScroll">
              <div v-for="(item, index) in dateList"
                   :key="index"
                   :class="['date-item', { 'is-active': item.date === selectedDate }]"
                   @click="handleDateSelect(item)">
                <div class="date-number">{{ item.month }}-{{ item.day }}</div>
                <div class="date-week">{{ item.weekDay }}</div>
              </div>
            </div>

            <!-- 右箭头 -->
            <div class="arrow-button right"
                 :class="{ disabled: !canScrollRight }"
                 @click="canScrollRight && scrollDates('right')">
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </div>

        <!-- 时间段选择 -->
        <div class="time-slots">
          <div class="time-slots-header">
            <div class="legend">
              <span class="legend-item">
                <div class="status-dot available"></div>
                <span>可预约</span>
              </span>
              <span class="legend-item">
                <div class="status-dot booked"></div>
                <span>已预约</span>
              </span>
              <span class="legend-item">
                <div class="status-dot selected"></div>
                <span>当前选择</span>
              </span>
            </div>
          </div>

          <div class="time-slots-grid">
            <el-button
              v-for="(slot, index) in timeSlots"
              :key="index"
              :type="getTimeSlotType(slot)"
              :disabled="slot.isBooked"
              @click="handleTimeSlotClick(slot)"
              class="time-slot-btn">
              <div class="time-slot-content">
                <span>{{ slot.start }} - {{ slot.end }}</span>
                <el-tooltip v-if="slot.appointInfo" placement="top">
                  <div slot="content">
                    <p>预约人：{{ slot.appointInfo.customerName }}</p>
                    <p>电话：{{ slot.appointInfo.phone }}</p>
                    <p>项目：{{ slot.appointInfo.productNames.join(', ') }}</p>
                  </div>
                  <i class="el-icon-info"></i>
                </el-tooltip>
              </div>
            </el-button>
          </div>
        </div>

        <!-- 预约表单 -->
        <el-form ref="appointForm" :model="form" :rules="rules" label-width="100px" class="appointment-form">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="预约类型" prop="apointType">
                <el-select v-model="form.apointType" placeholder="请选择预约类型">
                  <el-option
                    v-for="dict in dict.type.apoint_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="服务项目" prop="productIds">
                <el-select v-model="form.productIds" multiple placeholder="请选择服务项目">
                  <el-option
                    v-for="item in productOptions"
                    :key="item.id"
                    :label="item.productName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="预约人" prop="name">
                <el-input v-model="form.name" placeholder="请输入预约人姓名">
                  <template slot="append">
                    <el-dropdown @command="handleCustomerSelect">
                      <span class="el-dropdown-link">
                        选择客户<i class="el-icon-arrow-down el-icon--right"></i>
                      </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="select">选择店内客户</el-dropdown-item>
                        <el-dropdown-item command="member">选择微信会员</el-dropdown-item>
                        <el-dropdown-item command="newuser">新用户首次</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="form.phone" placeholder="请输入手机号" :disabled="!!form.customId">
                  <template slot="append">
                    <el-tag size="small" :type="getCustomerTypeTag(form.customType)">
                      {{ getCustomerTypeText(form.customType) }}
                    </el-tag>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <div class="form-footer">
          <el-button type="primary"
                     @click="submitAppointment"
                     :loading="submitLoading">
            {{ submitLoading ? '提交中...' : '确认预约' }}
          </el-button>
          <el-button @click="resetForm" :disabled="submitLoading">重置</el-button>
        </div>
      </el-card>

      <!-- 在 el-card 后面添加预约记录列表 -->
      <el-card class="box-card mt20" v-loading="listLoading">
        <div slot="header" class="clearfix">
          <span>预约记录</span>
        </div>

        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <el-tab-pane label="当前预约" name="current">
            <el-table v-loading="loading" :data="currentAppointments" border stripe>
              <el-table-column label="预约日期" align="center" prop="apointTime" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.apointTime, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="时间段" align="center" width="150">
                <template slot-scope="scope">
                  {{ scope.row.startHour }} - {{ scope.row.endHour }}
                </template>
              </el-table-column>
              <el-table-column label="预约类型" align="center" prop="apointType" width="120">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.apoint_type" :value="scope.row.apointType"/>
                </template>
              </el-table-column>
              <el-table-column label="服务项目" align="center" prop="productNames" />
              <el-table-column label="预约人" align="center" prop="nickname" width="120"/>
              <el-table-column label="手机号" align="center" prop="phone" width="120"/>
              <el-table-column label="订单状态" align="center" prop="ifOrder" width="120">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.if_order" :value="scope.row.ifOrder"/>
                </template>
              </el-table-column>
              <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip/>
            </el-table>
          </el-tab-pane>

          <el-tab-pane label="历史预约" name="history">
            <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form">
              <el-form-item label="预约日期">
                <el-date-picker
                  v-model="queryParams.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="预约类型">
                <el-select v-model="queryParams.apointType" placeholder="请选择预约类型" clearable>
                  <el-option
                    v-for="dict in dict.type.apoint_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-table v-loading="loading" :data="historyAppointments" border stripe>
              <!-- 表格列与当前预约相同 -->
              <el-table-column label="预约日期" align="center" prop="apointTime" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.apointTime, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="时间段" align="center" width="150">
                <template slot-scope="scope">
                  {{ scope.row.startHour }} - {{ scope.row.endHour }}
                </template>
              </el-table-column>
              <el-table-column label="预约类型" align="center" prop="apointType" width="120">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.apoint_type" :value="scope.row.apointType"/>
                </template>
              </el-table-column>
              <el-table-column label="服务项目" align="center" prop="productNames" />
              <el-table-column label="预约人" align="center" prop="nickname" width="120"/>
              <el-table-column label="手机号" align="center" prop="phone" width="120"/>
              <el-table-column label="订单状态" align="center" prop="ifOrder" width="120">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.if_order" :value="scope.row.ifOrder"/>
                </template>
              </el-table-column>
              <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip/>
            </el-table>

            <pagination
              v-show="total > 0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getHistoryList"
            />
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>

    <!-- 微信会员用户选择 -->
    <el-dialog
      title="选择微信会员"
      :visible.sync="memberDialogVisible"
      width="600px"
      :close-on-click-modal="false"
      :append-to-body="true"
      custom-class="select-dialog">
      <div class="dialog-content">
        <member-select @select="handleMemberSelected" />
      </div>
    </el-dialog>

    <!-- 店内客户资料选择 -->
    <el-dialog
      title="选择店内客户"
      :visible.sync="customerDialogVisible"
      width="600px"
      :close-on-click-modal="false"
      :append-to-body="true"
      custom-class="select-dialog">
      <div class="dialog-content">
        <customer-select @select="handleCustomerSelected" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSlApointForm, getSlApointForm, delSlApointForm,getProductOptions , addSlApointForm, updateSlApointForm, getAppointTime } from "@/api/projects/SlApointForm";
import { debounce } from '@/utils';
import CustomerSelect from '@/views/projects/SlCustomInfo/select.vue'
import MemberSelect from '@/views/projects/SlCustom/select.vue'

// 静态时间段数据
const staticTimeSlots = [
  {
    start: "09:00",
    end: "11:00",
    isBooked: false,
    isSelected: false,
    appointInfo: null
  },
  {
    start: "11:00",
    end: "13:00",
    isBooked: false,
    isSelected: false,
    appointInfo: null
  },
  {
    start: "13:00",
    end: "15:00",
    isBooked: false,
    isSelected: false,
    appointInfo: null
  },
  {
    start: "15:00",
    end: "17:00",
    isBooked: false,
    isSelected: false,
    appointInfo: null
  },
  {
    start: "17:00",
    end: "19:00",
    isBooked: false,
    isSelected: false,
    appointInfo: null
  },
  {
    start: "19:00",
    end: "21:00",
    isBooked: false,
    isSelected: false,
    appointInfo: null
  }
];

export default {
  name: "SlApointForm",
  dicts: ['apoint_type', 'if_order'],

  components: {
    'dict-tag': () => import('@/components/DictTag'),
    'pagination': () => import('@/components/Pagination'),
    CustomerSelect,
    MemberSelect
  },

  data() {
    return {
      loading: false,
      productOptions: [],
      dateList: [],
      selectedDate: new Date(),
      selectedSlot: null,
      timeSlots: staticTimeSlots,
      pickerOptions: Object.freeze({
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }]
      }),
      // 表单对象
      form: {
        apointType: '',
        productIds: [],
        name: '',
        remark: '',
        customId: null,
        phone: '',
        customType: ''
      },
      // 表单验证规则
      rules: {
        apointType: [
          { required: true, message: '请选择预约类型', trigger: 'change' }
        ],
        productIds: [
          { required: true, message: '请选择服务项目', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入预约人姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ]
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customId: null,
        productId: null,
        ifOrder: null,
        apointTime: null,
        dateRange: [],
        apointType: undefined

      },
      // 总条数
      total: 0,
      // 预约列表数据
      SlApointFormList: [],
      canScrollLeft: false,
      canScrollRight: true,
      // 添加标签页相关数据
      activeTab: 'current',  // 当前激活的标签页
      currentAppointments: [], // 当前预约列表
      historyAppointments: [], // 历史预约列表
      submitLoading: false, // 添加提交状态控制
      loading: false,        // 全局loading
      cardLoading: false,    // 卡片loading
      listLoading: false,    // 列表loading
      loadingText: '加载中...', // loading提示文本
      customerDialogVisible: false,  // 店内客户选择弹窗
      memberDialogVisible: false,    // 会员选择弹窗
      dialogTitle: '',              // 弹窗标题
    }
  },

  created() {
    this.$nextTick(() => {
      // 获取产品选项（优先从缓存获取）
      this.getProducts();
      this.initDateList();
      this.initTimeSlots();
      this.getCurrentList();
    });
  },

  mounted() {
    requestAnimationFrame(() => {
      const scrollContainer = this.$refs.dateScroll;
      if (scrollContainer) {
        scrollContainer.addEventListener('scroll', this.handleScroll, { passive: true });
        this.updateScrollButtons(scrollContainer);
      }
    });
  },

  methods: {
    handleScroll: debounce(function() {
      this.updateScrollButtons(this.$refs.dateScroll);
    }, 100),

    updateTimeSlotStatus(timeSlots) {
      if (!timeSlots?.length) return;

      const timeSlotMap = new Map(
        timeSlots.map(slot => [`${slot.startHour}-${slot.endHour}`, slot])
      );

      this.timeSlots.forEach(slot => {
        const key = `${slot.start}-${slot.end}`;
        const bookedSlot = timeSlotMap.get(key);

        if (bookedSlot) {
          slot.isBooked = bookedSlot.isBooked;
          slot.appointInfo = bookedSlot.appointInfo ? { ...bookedSlot.appointInfo } : null;
        } else {
          slot.isBooked = false;
          slot.appointInfo = null;
        }
        slot.isSelected = false;
      });
    },

    handleDateSelect(item) {
      if (this.selectedDate === item.date) return;
      this.selectedDate = item.date;
      this.resetTimeSlots();
      this.queryParams.apointTime = item.date;
      this.getDateAppointments(item.date);
    },

    // 处理客户选择
    handleCustomerSelect(command) {
      switch(command) {
        case 'select':
          this.selectCustomer();
          break;
        case 'member':
          this.selectMember();
          break;
        case 'newuser':
          this.selectStoreUser();
          break;
      }
    },

    // 选择店内客户
    selectCustomer() {
      this.dialogTitle = '选择店内客户';
      this.customerDialogVisible = true;
    },

    // 选择微信会员
    selectMember() {
      this.dialogTitle = '选择微信会员';
      this.memberDialogVisible = true;
    },

    // 处理店内客户选择
    handleCustomerSelected(customer) {
      if (customer) {
        this.form = {
          ...this.form,
          name: customer.name,
          phone: customer.phone,
          customId: customer.customId,
          customType: 1, // 店内客户预约类型
          isNewCustomer: false
        };
      }
      this.customerDialogVisible = false;
    },

    // 处理会员选择
    handleMemberSelected(member) {
      if (member) {
        this.form = {
          ...this.form,
          name: member.nickName || member.name,
          phone: member.phone,
          customId: member.customId,
          customType: 2, // 会员预约类型
          isNewCustomer: false
        };
      }
      this.memberDialogVisible = false;
    },

    // 新用户首次预约
    selectStoreUser() {
      this.$prompt('请输入新客户手机号', '新用户预约', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^1[3-9]\d{9}$/,
        inputErrorMessage: '手机号格式不正确',
        inputType: 'tel',
        inputPlaceholder: '请输入手机号'
      }).then(({ value: phone }) => {
        this.$prompt('请输入客户姓名', '新用户预约', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPlaceholder: '请输入姓名'
        }).then(({ value: name }) => {
          this.form = {
            ...this.form,
            phone,
            name,
            customId: null,
            customType: 3,
            isNewCustomer: true
          };
          this.$message.success('新客户信息已录入');
        }).catch(() => {
          this.form = {
            ...this.form,
            phone,
            name: '新客户-' + phone.substr(-4),
            customId: null,
            customType: 3,
            isNewCustomer: true
          };
        });
      });
    },

    /** 查询预约列表 */
    getApointList() {
      this.loading = true
      listSlApointForm(this.queryParams).then(response => {
        this.SlApointFormList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    // 获取时间段预约状态
    getTimeSlotStatus() {
      this.loading = true
      getAppointTime({
        apointTime: this.selectedDate
      }).then(res => {
        if (res.code === 200) {
          const { timeSlots, appointments, products } = res.data;
          console.log(timeSlots)
          if (timeSlots && Array.isArray(timeSlots)) {
            this.updateTimeSlotStatus(timeSlots);
          }
          console.log(products)
          if (products && Array.isArray(products)) {
            this.productOptions = products;
          }
          console.log(appointments)
          if (appointments && Array.isArray(appointments)) {
            this.currentAppointments = appointments;
          }
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    // 修改提交方法
    submitAppointment() {
      if (this.submitLoading) {
        this.$modal.msgWarning('数据正在提交，请勿重复请求');
        return;
      }

      if (!this.selectedSlot) {
        this.$modal.msgError('请选择预约时间段');
        return;
      }

      this.$refs.appointForm.validate(valid => {
        if (!valid) return;

        try {
          this.submitLoading = true;
          this.loadingText = '正在提交预约...';

          const appointmentData = {
            ...this.form,
            apointTime: this.selectedDate,
            startHour: this.selectedSlot.start,
            endHour: this.selectedSlot.end,
            productId: this.form.productIds.join(","),
          }
          addSlApointForm(appointmentData, {
            headers: {
              'repeatSubmit': false
            }
          }).then(res => {
            if (res.code === 200) {
              this.$modal.msgSuccess('预约成功');
              this.resetForm();
              this.getDateAppointments(this.selectedDate);
            } else {
              this.$modal.msgError(res.msg || '预约失败');
            }
          }).catch(error => {
            this.$modal.msgError(error.message || '预约失败');
          }).finally(() => {
            this.submitLoading = false;
            this.loadingText = '加载中...';
          });
        } catch (error) {
          this.submitLoading = false;
          this.loadingText = '加载中...';
          this.$modal.msgError('系统错误：' + error.message);
        }
      });
    },

    // 处理时间段点击
    handleTimeSlotClick(slot) {
      if (slot.isBooked) {
        // 如果已预约，显示预约信息
        if (slot.appointInfo) {
          this.$modal.msgInfo(`该时段已被预约\n预约人：${slot.appointInfo.customerName}\n项目：${slot.appointInfo.productNames.join(', ')}`);
        }
        return;
      }

      // 取消之前选中的时间段
      this.timeSlots.forEach(s => s.isSelected = false);

      // 设置当前选中的时间段
      slot.isSelected = true;
      this.selectedSlot = slot;

      // 更新表单数据
      this.form.startHour = slot.start;
      this.form.endHour = slot.end;
    },

    // 获取时间段按钮类型
    getTimeSlotType(slot) {
      if (slot.isSelected) return 'primary';
      if (slot.isBooked) return 'info';
      return '';
    },

    // 重置表单时同时重置时间段选择
    resetForm() {
      this.submitLoading = false; // 重置提交状态
      this.$refs.appointForm.resetFields();
      this.timeSlots.forEach(slot => {
        slot.isSelected = false;
      });
      this.selectedSlot = null;
      this.form = {
        apointType: '',
        productIds: [],
        name: '',
        remark: '',
        customId: null,
        phone: '',
        startHour: '',
        endHour: '',
        customType:''
      };
    },

    // 添加 formatDate 方法
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 重置时间段状态
    resetTimeSlots() {
      if (!this.timeSlots) return;

      this.timeSlots.forEach(slot => {
        slot.isSelected = false;
        slot.isBooked = false;
        slot.appointInfo = null;
      });

      // 重置选中状态
      this.selectedSlot = null;
      if (this.form) {
        this.form.startHour = '';
        this.form.endHour = '';
      }
    },

    // 获取指定日期的预约数据
    getDateAppointments(date) {
      this.cardLoading = true;
      this.loadingText = '获取预约数据...';

      getAppointTime({
        apointTime: date
      }).then(res => {
        if (res.code === 200) {
          const { timeSlots, appointments } = res.data;

          if (timeSlots && Array.isArray(timeSlots)) {
            this.updateTimeSlotStatus(timeSlots);
          }

          if (appointments && Array.isArray(appointments)) {
            this.currentAppointments = appointments;
          }
        } else {
          this.$modal.msgError(res.msg || '获取预约数据失败');
        }
      }).catch(error => {
        this.$modal.msgError('获取预约数据失败：' + error.message);
      }).finally(() => {
        this.cardLoading = false;
        this.loadingText = '加载中...';
      });
    },

    // 修改滚动方法
    scrollDates(direction) {
      const scrollContainer = this.$refs.dateScroll;
      const scrollAmount = 320;

      if (direction === 'left') {
        scrollContainer.scrollLeft -= scrollAmount;
      } else {
        scrollContainer.scrollLeft += scrollAmount;
      }

      // 更新滚动状态
      this.$nextTick(() => {
        this.updateScrollButtons(scrollContainer);
      });
    },

    // 添加滚动状态更新方法
    updateScrollButtons(container) {
      if (!container) return;

      this.canScrollLeft = container.scrollLeft > 0;
      this.canScrollRight =
        container.scrollLeft < (container.scrollWidth - container.clientWidth);
    },

    // 处理标签页切换
    handleTabClick(tab) {
      if (tab.name === 'current') {
        this.getCurrentList();
      } else {
        this.getHistoryList();
      }
    },

    // 获取当前预约列表
    getCurrentList() {
      this.listLoading = true;
      listSlApointForm({
        ...this.queryParams,
        isHistory: false,
        apointTime: this.selectedDate
      }).then(response => {
        this.currentAppointments = response.rows;
        this.total = response.total;
      }).catch(() => {
        this.$modal.msgError('获取列表数据失败');
      }).finally(() => {
        this.listLoading = false;
      });
    },

    // 获取历史预约列表
    getHistoryList() {
      this.loading = true;
      listSlApointForm({
        ...this.queryParams,
        isHistory: true,
        beginTime: this.queryParams.dateRange ? this.queryParams.dateRange[0] : undefined,
        endTime: this.queryParams.dateRange ? this.queryParams.dateRange[1] : undefined
      }).then(response => {
        this.historyAppointments = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getHistoryList();
    },

    // 重置按钮操作
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.dateRange = [];
      this.queryParams.apointType = undefined;
      this.handleQuery();
    },

    // 初始化日期列表
    initDateList() {
      const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      const today = new Date();

      // 生成未来30天的日期列表
      this.dateList = Array.from({ length: 30 }, (_, index) => {
        const date = new Date(today);
        date.setDate(today.getDate() + index);

        return {
          date: this.formatDate(date),
          month: date.getMonth() + 1,
          day: date.getDate(),
          weekDay: weekDays[date.getDay()]
        };
      });

      // 设置默认选中今天
      this.selectedDate = this.dateList[0].date;
      // 获取今天的预约数据
      this.getTimeSlotStatus();
    },

    // 初始化时间段
    initTimeSlots() {
      // 只需要重置状态
      this.timeSlots.forEach(slot => {
        slot.isBooked = false;
        slot.isSelected = false;
        slot.appointInfo = null;
      });
    },

    // 获取产品选项
    async getProducts() {
      try {
        // 获取缓存和缓存时间
        const cachedData = localStorage.getItem('productOptionsData');
        if (cachedData) {
          const { data, timestamp } = JSON.parse(cachedData);
          // 检查缓存是否在24小时内
          if (Date.now() - timestamp < 24 * 60 * 60 * 1000) {
            this.productOptions = data;
            return;
          }
        }

        // 缓存过期或不存在，请求新数据
        const res = await getProductOptions();
        if (res.code === 200) {
          this.productOptions = res.data;
          // 存入缓存，带时间戳
          localStorage.setItem('productOptionsData', JSON.stringify({
            data: res.data,
            timestamp: Date.now()
          }));
        } else {
          this.$modal.msgError(res.msg || '获取产品选项失败');
        }
      } catch (error) {
        this.$modal.msgError('获取产品选项失败：' + error.message);
      }
    },

    // 清除产品选项缓存
    clearProductsCache() {
      localStorage.removeItem('productOptionsData');
    },

    // 获取客户类型标签样式
    getCustomerTypeTag(type) {
      switch(type) {
        case 1: return 'success';  // 店内客户
        case 2: return 'primary';  // 微信会员
        case 3: return 'warning';  // 新用户
        default: return 'info';
      }
    },

    // 获取客户类型文本
    getCustomerTypeText(type) {
      switch(type) {
        case 1: return '店内客户';
        case 2: return '微信会员';
        case 3: return '新用户';
        default: return '未选择';
      }
    }
  },

  beforeDestroy() {
    this.submitLoading = false;
    // 组件销毁时清除缓存
    this.clearProductsCache();
  }
}
</script>

<style lang="scss" scoped>
:root {
  --primary-color: #409eff;
  --border-color: #dcdfe6;
  --bg-color: #f5f7fa;
  --text-color: #606266;
  --disabled-color: #c0c4cc;
}

.app-container {
  height: calc(100vh - 84px);
  overflow-y: auto;
  padding: 10px 20px;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: var(--border-color);
    border-radius: 3px;
  }

  &::-webkit-scrollbar-track {
    background-color: var(--bg-color);
  }
}

.date-scroll {
  will-change: scroll-position;
  -webkit-overflow-scrolling: touch;
  display: flex;
  overflow-x: auto;
  scroll-behavior: smooth;
  padding: 10px 30px;
  margin: 0 20px;

  &::-webkit-scrollbar {
    display: none;
  }
}

.date-item {
  transition: transform 0.3s;

  &:hover {
    transform: translateY(-2px);
  }

  &.is-active {
    background-color: var(--primary-color);
    border-color: var(--primary-color);
    color: #fff;
  }
}

.time-slots-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  gap: 10px;

  > .time-slot-btn {
    height: 40px;

    &.is-disabled {
      background-color: var(--bg-color) !important;
      border-color: var(--border-color) !important;
      color: var(--disabled-color) !important;
    }
  }
}

.date-picker {
  margin: 20px 0;
  padding: 0 10px;
  position: relative;

  .date-picker-wrapper {
    position: relative;
    display: flex;
    align-items: center;
    background: #fff;

    .arrow-button {
      position: absolute;
      width: 32px;
      height: 32px;
      background-color: #fff;
      border: 1px solid #dcdfe6;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      z-index: 2;
      transition: all 0.3s;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

      &:hover {
        background-color: #f5f7fa;
        color: #409eff;
        border-color: #409eff;
      }

      &.left {
        left: -6px;
      }

      &.right {
        right: -6px;
      }

      i {
        font-size: 16px;
        font-weight: bold;
      }

      &.disabled {
        cursor: not-allowed;
        opacity: 0.5;
        &:hover {
          background-color: #fff;
          color: #606266;
          border-color: #dcdfe6;
        }
      }
    }
  }

  .date-scroll {
    display: flex;
    overflow-x: auto;
    scroll-behavior: smooth;
    padding: 10px 30px;
    margin: 0 20px;
    -ms-overflow-style: none;
    scrollbar-width: none;
    position: relative;
    background: #fff;
    border-radius: 4px;

    &::-webkit-scrollbar {
      display: none;
    }

    .date-item {
      flex: 0 0 auto;
      width: 80px;
      height: 70px;
      margin-right: 12px;
      border: 1px solid #dcdfe6;
      border-radius: 8px;
      cursor: pointer;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      transition: all 0.3s;
      background-color: #fff;

      &:hover {
        border-color: #409eff;
        transform: translateY(-2px);
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      }

      &.is-active {
        background-color: #409eff;
        border-color: #409eff;
        color: #fff;
        transform: translateY(-2px);
        box-shadow: 0 2px 12px 0 rgba(64, 158, 255, 0.3);
      }

      .date-number {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 4px;
      }

      .date-week {
        font-size: 12px;
        color: inherit;
        opacity: 0.8;
      }
    }
  }
}

.time-slots {
  margin: 20px 0;

  .time-slots-header {
    margin-bottom: 15px;

    .legend {
      display: flex;
      justify-content: center;
      gap: 30px;

      .legend-item {
        display: flex;
        align-items: center;

        .status-dot {
          width: 12px;
          height: 12px;
          border-radius: 50%;
          margin-right: 8px;

          &.available {
            background-color: #67c23a;
          }

          &.booked {
            background-color: #909399;
          }

          &.selected {
            background-color: #409eff;
          }
        }
      }
    }
  }

  .time-slots-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
    gap: 10px;
    padding: 15px;
    background-color: #f5f7fa;
    border-radius: 4px;

    .time-slot-btn {
      height: 40px;
      padding: 0 15px;

      &.is-disabled {
        color: #c0c4cc;
        background-color: #f5f7fa;
        border-color: #e4e7ed;
      }

      &:hover:not(.is-disabled) {
        opacity: 0.8;
      }
    }
  }
}

.appointment-form {
  margin-top: 30px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.form-footer {
  margin-top: 20px;
  text-align: center;
}

// 修改loading样式
.el-loading-spinner {
  .el-loading-text {
    color: #fff;
    margin: 3px 0;
    font-size: 14px;
  }
}

.el-loading-mask {
  background-color: rgba(0, 0, 0, 0.7);
}

.custom-dialog {
  .el-dialog__body {
    padding: 20px;
  }

  .el-dialog__footer {
    text-align: right;
  }
}

.select-dialog {
  ::v-deep .el-dialog {
    margin-top: 15vh !important;

    .el-dialog__body {
      padding: 10px 20px;
      max-height: 400px;
      height: auto;
      overflow-y: auto;
    }

    .el-dialog__header {
      padding: 12px 20px;
      background-color: #f5f7fa;
      border-bottom: 1px solid #e4e7ed;
      margin: 0;
    }

    .dialog-content {
      padding: 10px 0;
    }
  }
}

// 优化滚动条样式
::v-deep .el-dialog__body::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::v-deep .el-dialog__body::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
}

::v-deep .el-dialog__body::-webkit-scrollbar-track {
  background: #f5f7fa;
}
</style>

